<template>
	<div class="wareHous-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="仓库代码">
					<el-input v-model="state.queryParams.code" placeholder="仓库代码" clearable />
				</el-form-item>
				<el-form-item label="仓库名称">
					<el-input v-model="state.queryParams.name" placeholder="仓库名称" clearable />
				</el-form-item>
				<el-form-item label="启用状态">
					<el-select v-model="state.queryParams.Isenable" placeholder="请选择">
						<el-option label="启用" value="1" />
						<el-option label="未启用" value="0"  />
<el-option label="全部" value="" :selected="state.queryParams.Isenable === undefined" />
						
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery" > 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Plus" @click="addWare"
							>添加</el-button>
							<el-button type="primary" icon="ele-Download" @click="downloadTemplate"
							>模版</el-button>
							<el-button type="primary" icon="ele-Download" @click="exportWare"
							>导出</el-button>
					<el-button type="danger"  icon="ele-Warning" @click="batchDeleteWcs">批量删除</el-button>

					</el-button-group>
					
				</el-form-item>

				<el-form-item>
					<!-- <el-upload>
							<el-button type="primary" icon="ele-Upload" @click="ImportWare"
								 style="margin-bottom: -70px;">导入1</el-button>
							<input ref="fileInput" type="file" hidden accept=".xlsx,.xls" @change="ImportWare" />
						</el-upload> -->
		<el-upload class="upload-demo" :http-request="handleUpload" :show-file-list="false" :before-upload="beforeUpload"
						:on-success="handleUploadSuccess" :on-error="handleUploadError">

						<el-button icon="ele-Upload" >导入</el-button>
					</el-upload>
				</el-form-item>

			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.wareHousData" style="width: 100%" v-loading="state.loading" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" prop="id" width="55" align="center" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="code" label="仓库代码" align="center" show-overflow-tooltip />
				<el-table-column prop="name" label="仓库名称" align="center" show-overflow-tooltip />
				<el-table-column prop="createUserName" label="创建人" align="center" show-overflow-tooltip />
				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
				<el-table-column prop="description" label="描述" align="center" show-overflow-tooltip />

				<el-table-column prop="isEnable" label="启用状态" width="80" align="center">
					<template #default="scope">
						<el-tag v-if="scope.row.isenable === 1"> 启用 </el-tag>
						<el-tag type="danger" v-else> 未启用 </el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="140" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditWarehous(scope.row)"
							> 编辑 </el-button>
						<el-button size="small" text type="danger" @click="delWarehous(scope.row)"
							> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditWarehous ref="editWarehousRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="wareHous">
import { onMounted, computed, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditWarehous from './component/editWarehouse.vue';
import { getAPI } from '/@/utils/axios-utils';
import { WarehouseApi,WarehouseinportApi,DownloadWarehousePositionApi,BatchDeletWarehouseAPi } from '/@/api-services/apis/warehouse-api'; // 导入 API 服务
import { WarehouseInput } from '/@/api-services/models/warehouse-input'; // 导入获取实体
import { downloadByData, getFileName } from '/@/utils/download';

import { error } from 'console';
import { number } from 'echarts';

// ...其他导入

const editWarehousRef = ref<InstanceType<typeof EditWarehous>>();
const state = reactive({
	loading: false,
	wareHousData: [] as Array<WarehouseInput>,
	queryParams: {
		name: undefined,
		code: undefined,
		Isenable: undefined,
	},

	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editWarehousTitle: '',

});

onMounted(async () => {
	//console.log('当前路由参数:', route); // 添加路由参数调试
	handleQuery();

});




// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {

		const res = await getAPI(WarehouseApi).apiWarehousePagePost({
			...state.queryParams,
			page: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.wareHousData = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.wareHousData = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.name = undefined
	state.queryParams.code = undefined
	handleQuery();
};

// 打开新增页面
const addWare = () => {
	const addData = {
		description: null,
		total: null,
		attachment: null,
		isenable: 1,
	};
	state.editWarehousTitle = '添加维护信息';
	editWarehousRef.value?.openDialog(addData);
};
//导出
const exportWare = async () => {

	try {
		state.loading = true;
// 由于 WarehouseOutput 类型要求 Isenable 为 number 类型，这里将其默认值设为 0（假设 0 代表全部）
const queryParamsWithValidType = {
  ...state.queryParams,
  Isenable: state.queryParams.Isenable === undefined ? 0 : state.queryParams.Isenable
};
var res = await getAPI(WarehouseApi).apiSysLogOpExportPost(queryParamsWithValidType, { responseType: 'blob' });
		state.loading = false;
		var fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
};
// 假设存在一个方法可以获取选中行的数据，这里我们先定义一个 ref 来存储选中的行
const multipleSelection = ref<WarehouseInput[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 获取选中行的 idlist
const selectedIds = computed(() => multipleSelection.value.map(item => item.id));

const batchDeleteWcs = async () => {
	if (selectedIds.value.length === 0) {
		ElMessage.warning('请选择要删除的1行');
		return;
	}
	//console.log(selectedIds.value);
// 由于找不到 then 方法，推测这里应该是在确认框调用后，需要将确认框逻辑移到正确位置
// 假设前面应该有 ElMessageBox.confirm 的调用，这里补充完整
try {
  const confirmResult = await ElMessageBox.confirm(
    '确定要批量删除选中的仓库吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  );
  if (confirmResult === 'confirm') {
    await BatchDeletWarehouseAPi(selectedIds.value.map(id => ({ id: id })));
    handleQuery(); // 刷新表格数据
    ElMessage.success('批量删除成功');
  }
} catch (error) {
  if (error === 'cancel') {
    ElMessage.info('已取消批量删除');
  } else {
    ElMessage.error('批量删除失败');
  }
}
};
// 关闭新增页面
const closeAddDialog = () => {
	editWarehousRef.value?.openDialog(false);
};


// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editWarehousTitle = '编辑仓库档案';
	editWarehousRef.value?.openDialog(row);
};

// 删除操作
const delWarehous = (row: any) => {
	ElMessageBox.confirm(`确定删除仓库：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}) 
		.then(async () => {
			try {
				await getAPI(WarehouseApi).apiWarehouseDeletePost({ id: row.id });
				handleQuery();
				ElMessage.success('删除成功');
			} catch (error) {
				//.error('删除失败:', error);
				ElMessage.error('删除失败，请稍后重试');
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};

// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
  
    const formData = new FormData()
    formData.append('file', options.file)
    // 这里调用你的上传API
try {
  const response = await WarehouseinportApi(formData);
  handleUploadSuccess(response);
} catch (error) {
  handleUploadError(error);
}
}
    

// 上传成功回调
const handleUploadSuccess = (response: any) => {
  if (response.status === 200) {
    ElMessage.success('导入成功')
    handleQuery() // 刷新表格数据
  } 
  else {
    ElMessage.error('导入失败')
  }
}

// 上传失败回调
const handleUploadError = (error:any) => {
	  ElMessage.error(error.message || '导入失败'+error.message)
}

const downloadTemplate = async () => {
  try {
     DownloadWarehousePositionApi().then((response)=>{
		
     const blob=new Blob([response.data])
	 const fileName=getFileName(response.headers);
	 downloadByData(response.data as any, fileName);
	
     ElMessage.success(`下载成功${fileName}`);
	 }); // 调用下载模板的API

  } catch (error) {
    ElMessage.error('下载失败');
  }
};







// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
